import '../public/index'
import url from '../data/url'
import {getUrlParam} from '../data/util'
import request from '../data/request'
import {header} from '../data/config'

import {
  userName   as valid_userName,
  password   as valid_password,
  contacts   as valid_contacts,
  mobile     as valid_mobile
} from '../data/validate'

const base = url.base,
  editOperator = request.editOperator,
  getOperatorRoleArea = request.getOperatorRoleArea,
  getOperatorDetail = request.getOperatorDetail,
  getOperatorBuild = request.getOperatorBuild,
  getOperatorRole = request.getOperatorRole;

let id = getUrlParam('id');

// 页面标题
const title = '操作员',
  action = '修改';

let form = new Vue({
  el: '#form',
  data: () => {
    return ({
      id: '',
      loginName: '',
      realName: '',
      phone: '',
      email: '',
      roleIds: '',
      roleList: '',
      dataRole: 1,
      areaId: '',
      areaList: '',
      buildingIds: [],
      buildingList: '',
      isLock: true
    })
  },
  mounted: function () {

    let that = this;

    that.getRole();
    that.getArea();

    setTimeout(() => {

      if (!id) {
        layer.msg('页面跳转错误', {
          icon: 5
        })

        window.location = './index.html'
      }

      that.initPge();

    }, 0)

    valid();

  },
  methods: {
    // 获取角色列表
    getRole: () => {

      let loading = layer.msg('初始化数据中...', {
        icon: 16,
        time: 0
      });

      $.ajax({
        url: base + getOperatorRole,
        headers: header
      })
        .done(function (res) {
          if (res.code === 0) {
            console.log('初始化角色列表成功');

            form.roleList = res.object;
          }else {
            console.log(res.error || '初始化角色数据失败')

          }
        })
        .fail(function (res) {
          console.log(res.error || '初始化角色数据失败')

        })
        .always(function (res) {
          layer.close(loading);

        })
    },
    // 获取区域列表
    getArea: () => {

      let loading = layer.msg('初始化数据中...', {
        icon: 16,
        time: 0
      });

      $.ajax({
        url: base + getOperatorRoleArea,
        headers: header
      })
        .done(function (res) {
          if (res.code === 0) {
            console.log('初始化区域列表成功');

            form.isLock = false;
            form.areaList = res.object;
          } else {
            console.log(res.error || '初始化区域数据失败')
            form.isLock = true;
          }
        })
        .fail(function (res) {
          console.log(res.error || '初始化区域数据失败')

        })
        .always(function (res) {
          layer.close(loading)

        })
    },
    // 获取楼盘列表
    getBuild: (city) => {
      let loading = layer.msg('初始化数据中...', {
        icon: 16,
        time: 0
      });

      $.ajax({
        url: base + getOperatorBuild,
        headers: header,
        data: {
          areaId: city,
          enterId: ''
        }
      })
        .done(function (res) {
          console.log('获取楼盘成功');

          form.buildingList = res.buildings

        })
        .fail(function (res) {
          let error = res.error;
          layer.msg(error || '获取楼盘失败', {
            icon: 5
          })
        })
        .always(function () {
          layer.close(loading)
        })
    },
    // 编辑页面初始之前数据
    initPge: function () { // 重置密码

      $.ajax({
        type: 'POST',
        headers: header,
        url: base + getOperatorDetail,
        data: { id: id}
      })
        .done(function (res) {
          console.log("初始化数据 success");
          console.log(res);

            form.loginName     = res.object.loginName;
            form.loginPassword = res.object.loginPassword;
            form.realName      = res.object.realName;
            form.phone         = res.object.phone;
            form.email         = res.object.email;
            form.roleIds       = res.object.roleIds ? res.object.roleIds[0] : '';
            form.dataRole      = res.object.dataRole;
            form.areaId        = res.object.areaId;
            form.buildingIds   = res.object.buildingIds ? res.object.buildingIds.split(',') : [];
            form.id            = res.object.id;

          console.log(form.$data);

          if(form.dataRole === 3 && form.buildingIds.length !== 0){
            console.log(form.buildingIds);
            console.log(form.areaId);
            form.getBuild(form.areaId ? form.areaId : '');
          }

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('初始化数据失败', {
            icon: 5
          });

          console.log("error")
        })
        .always(function (res) {

          console.log("complete")
        })

    }
  }
})

function valid() {

  let form_valid,
      $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      console.log(form.$data);

      let roleArr= new Array;
      roleArr.push(form.roleIds);

      form.isLock = true

      $.ajax({
        url: base + editOperator,
        type: 'POST',
        headers: header,
        contentType: 'application/json',
        data: JSON.stringify({
          loginName: form.loginName ? form.loginName : '' ,
          loginPassword: form.loginPassword ? form.loginPassword : '' ,
          realName: form.realName ? form.realName : '' ,
          phone: form.phone ? form.phone : '' ,
          email: form.email ? form.email : '' ,
          roleIds: form.roleIds ? roleArr : '' ,
          roleName: form.roleIds ? $(`input[name=roleIds][value=${form.roleIds}]`).text() : '' ,
          dataRole: form.dataRole ? form.dataRole : '' ,
          areaId: form.areaId ? form.areaId : '' ,
          buildingIds: form.buildingIds ? form.buildingIds.join(',') : '' ,
          id: form.id,
        })
      })
        .done(function (res) {
          console.log(res)

          if (res.code === -1) {
            layer.msg(res.message, {
              icon: 5
            })

            return
          }

          layer.msg(`${action}${ title }成功`, {
            icon: 6
          })

          // 重置表单
          $.extend(form.$data, form.$options.data())

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)
        })
        .fail(function (res) {
          console.log(res)

          layer.msg(`${action}${ title }失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function (res) {

          layer.close(loading_modal)
          form.isLock = false

        })

    }
  })

  // 验证
  form_valid = $form.validate({
    errorPlacement: function (error, element) {
      error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      roleIds: {
        required: true
      },
      email: {
        email: true
      },
      realName: valid_contacts,
      loginName: valid_userName,
      loginPassword: valid_password,
      phone: valid_mobile,
    }
  })

}